//
//  ContentView.swift
//  test
//
//  Created by 下坠 on 2025/3/25.
//

import SwiftUI





// 本地化字符串扩展
extension String {
    var localized: String {
        // 获取当前语言设置
        let currentLanguage: Language
        if let savedLanguage = UserDefaults.standard.string(forKey: "selectedLanguage"),
           let language = Language(rawValue: savedLanguage) {
            currentLanguage = language
        } else {
            currentLanguage = .chinese
        }
        
        // 根据当前语言获取对应的本地化文件
        let bundle: Bundle
        switch currentLanguage {
        case .english:
            if let path = Bundle.main.path(forResource: "en", ofType: "lproj"),
               let langBundle = Bundle(path: path) {
                bundle = langBundle
            } else {
                bundle = Bundle.main
            }
        case .uyghur:
            if let path = Bundle.main.path(forResource: "ug", ofType: "lproj"),
               let langBundle = Bundle(path: path) {
                bundle = langBundle
            } else {
                bundle = Bundle.main
            }
        case .chinese:
            if let path = Bundle.main.path(forResource: "zh-Hans", ofType: "lproj"),
               let langBundle = Bundle(path: path) {
                bundle = langBundle
            } else {
                bundle = Bundle.main
            }
        }
        
        return NSLocalizedString(self, bundle: bundle, comment: "")
    }
}

struct ContentView: View {
    @EnvironmentObject var languageManager: LanguageManager
    @EnvironmentObject var themeManager: ThemeManager
    @State private var showWelcome = false
    @State private var selectedLanguage: Language = .chinese
    @State private var refreshTrigger = false
    
    init() {
        // 检查是否是首次启动
        if !UserDefaults.standard.bool(forKey: "hasLaunchedBefore") {
            _showWelcome = State(initialValue: true)
        }
    }
    
    var body: some View {
        ZStack {
            TabView {
                BillListPage()
                    .tabItem {
                        Image(systemName: "list.bullet")
                        Text("账单".localized)
                            .lineLimit(1)
                            .minimumScaleFactor(0.8)
                    }
                    .id(refreshTrigger)
                
                StatisticsPage()
                    .tabItem {
                        Image(systemName: "chart.pie")
                        Text("统计".localized)
                            .lineLimit(1)
                            .minimumScaleFactor(0.8)
                    }
                    .id(refreshTrigger)
                
                SettingsPage()
                    .tabItem {
                        Image(systemName: "gear")
                        Text("设置".localized)
                            .lineLimit(1)
                            .minimumScaleFactor(0.8)
                    }
                    .id(refreshTrigger)
            }
            .environmentObject(themeManager)
            .environmentObject(languageManager)
            
            // 欢迎页面覆盖层
            if showWelcome {
                WelcomeView(showWelcome: $showWelcome, selectedLanguage: $selectedLanguage)
                    .transition(.opacity.combined(with: .scale))
            }
        }
        .onReceive(NotificationCenter.default.publisher(for: NSNotification.Name("LanguageChanged"))) { _ in
            // 语言变化时刷新界面
            withAnimation(.easeInOut(duration: 0.3)) {
                // 强制刷新界面
                languageManager.objectWillChange.send()
                refreshTrigger.toggle()
            }
        }
    }
}

// 欢迎页面
struct WelcomeView: View {
    @Binding var showWelcome: Bool
    @Binding var selectedLanguage: Language
    @EnvironmentObject var languageManager: LanguageManager
    
    var body: some View {
        ZStack {
            // 背景
            Color(.systemBackground)
                .ignoresSafeArea()
            
            VStack(spacing: 40) {
                Spacer()
                
                // App图标和名称
                VStack(spacing: 20) {
                    Image(systemName: "creditcard.fill")
                        .font(.system(size: 80))
                        .foregroundColor(.gray)
                    
                    Text("记账App")
                        .font(.largeTitle)
                        .fontWeight(.bold)
                        .foregroundColor(.primary)
                    
                    Text("选择您的语言")
                        .font(.title3)
                        .foregroundColor(.secondary)
                        .lineLimit(1)
                        .minimumScaleFactor(0.8)
                }
                
                // 语言选择按钮
                VStack(spacing: 16) {
                    ForEach(Language.allCases, id: \.self) { language in
                        Button(action: {
                            selectedLanguage = language
                        }) {
                            HStack {
                                Text(language.flag)
                                    .font(.title2)
                                    .frame(width: 30)
                                
                                Text(language.displayName)
                                    .font(.body)
                                    .foregroundColor(.primary)
                                    .lineLimit(1)
                                    .minimumScaleFactor(0.8)
                                
                                Spacer()
                                
                                if selectedLanguage == language {
                                    Image(systemName: "checkmark.circle.fill")
                                        .foregroundColor(.gray)
                                }
                            }
                            .padding(.horizontal, 20)
                            .padding(.vertical, 16)
                            .background(
                                RoundedRectangle(cornerRadius: 12)
                                    .fill(selectedLanguage == language ? Color.gray.opacity(0.1) : Color.clear)
                                    .overlay(
                                        RoundedRectangle(cornerRadius: 12)
                                            .stroke(selectedLanguage == language ? Color.gray.opacity(0.3) : Color.clear, lineWidth: 1)
                                    )
                            )
                        }
                        .buttonStyle(PlainButtonStyle())
                    }
                }
                .padding(.horizontal, 40)
                
                // 开始使用按钮
                Button(action: {
                    // 保存语言选择
                    languageManager.setLanguage(selectedLanguage)
                    UserDefaults.standard.set(selectedLanguage.rawValue, forKey: "selectedLanguage")
                    // 标记已启动
                    UserDefaults.standard.set(true, forKey: "hasLaunchedBefore")
                    // 隐藏欢迎页面
                    withAnimation(.easeInOut(duration: 0.5)) {
                        showWelcome = false
                    }
                }) {
                    Text("开始使用")
                        .font(.headline)
                        .fontWeight(.semibold)
                        .foregroundColor(.white)
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 16)
                        .background(
                            RoundedRectangle(cornerRadius: 12)
                                .fill(Color.gray)
                        )
                }
                .padding(.horizontal, 40)
                
                Spacer()
            }
        }
    }
}

struct BillListPage: View {
    @EnvironmentObject var languageManager: LanguageManager
    @Environment(\.horizontalSizeClass) var horizontalSizeClass
    @State private var bills: [Bill] = BillListPage.loadBills()
    @State private var showAddSheet = false
    @State private var editBill: Bill? = nil
    @State private var animateAdd = false
    @State private var animateDelete = false
    
    static func loadBills() -> [Bill] {
        if let data = UserDefaults.standard.data(forKey: "bills"),
           let arr = try? JSONDecoder().decode([Bill].self, from: data) {
            return arr
        }
        return []
    }
    func saveBills() {
        if let encoded = try? JSONEncoder().encode(bills) {
            UserDefaults.standard.set(encoded, forKey: "bills")
            // 发送通知，让统计页面更新数据
            NotificationCenter.default.post(name: NSNotification.Name("BillsUpdated"), object: nil)
        }
    }
    var totalIncome: Double {
        bills.filter { $0.type == .income && Calendar.current.isDate($0.date, equalTo: Date(), toGranularity: .month) }.map { $0.amount }.reduce(0, +)
    }
    var totalExpense: Double {
        bills.filter { $0.type == .expense && Calendar.current.isDate($0.date, equalTo: Date(), toGranularity: .month) }.map { $0.amount }.reduce(0, +)
    }
    var totalBalance: Double { totalIncome - totalExpense }
    // 按日期分组账单
    typealias GroupedBills = [(String, [Bill])]
    var groupedBills: GroupedBills {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        let groups = Dictionary(grouping: bills) { formatter.string(from: $0.date) }
        return groups.sorted { $0.key > $1.key }
    }
    var body: some View {
        NavigationStack {
            ZStack(alignment: .bottomTrailing) {
                VStack(spacing: 12) {
                    // 顶部收支总览卡片（黑白灰极简风格）
                    HStack {
                        VStack(alignment: .leading, spacing: 4) {
                            Text("本月收入".localized)
                                .font(.caption)
                                .foregroundColor(.secondary)
                            Text("+\(String(format: "%.2f", totalIncome))")
                                .font(.title2)
                                .foregroundColor(.primary)
                                .lineLimit(1)
                                .minimumScaleFactor(0.7)
                        }
                        Spacer()
                        VStack(alignment: .leading, spacing: 4) {
                            Text("本月支出".localized)
                                .font(.caption)
                                .foregroundColor(.secondary)
                            Text("-\(String(format: "%.2f", totalExpense))")
                                .font(.title2)
                                .foregroundColor(.primary)
                                .lineLimit(1)
                                .minimumScaleFactor(0.7)
                        }
                        Spacer()
                        VStack(alignment: .leading, spacing: 4) {
                            Text("结余".localized)
                                .font(.caption)
                                .foregroundColor(.secondary)
                            Text("\(String(format: "%.2f", totalBalance))")
                                .font(.title2)
                                .foregroundColor(.primary)
                                .lineLimit(1)
                                .minimumScaleFactor(0.7)
                        }
                    }
                    .padding()
                    .background(
                        RoundedRectangle(cornerRadius: 18)
                            .fill(Color(.systemGray6))
                    )
                    .shadow(color: Color.black.opacity(0.05), radius: 6, x: 0, y: 2)
                    .padding(.horizontal)
                    .scaleEffect(animateAdd ? 1.02 : 1.0)
                    .animation(.easeInOut(duration: 0.3), value: animateAdd)
                    
                    // 账单列表或空状态
                    if bills.isEmpty {
                        Spacer()
                        VStack(spacing: 12) {
                            Image(systemName: "tray.fill")
                                .resizable()
                                .frame(width: 80, height: 80)
                                .foregroundColor(.gray.opacity(0.2))
                                .scaleEffect((horizontalSizeClass == .regular) ? 1.0 : (animateAdd ? 1.1 : 1.0))
                                .animation((horizontalSizeClass == .regular) ? nil : .easeInOut(duration: 0.5).repeatForever(autoreverses: true), value: animateAdd)
                            Text("暂无账单，点击右下角添加".localized)
                                .foregroundColor(.secondary)
                                .font(.title3)
                                .multilineTextAlignment(.center)
                                .minimumScaleFactor(0.8)
                        }
                        .onAppear {
                            if horizontalSizeClass != .regular { animateAdd = true }
                        }
                        Spacer()
                    } else {
                        List {
                            ForEach(groupedBills, id: \.0) { (date, bills) in
                                Section(header: Text(date).font(.headline).foregroundColor(.gray)) {
                                    ForEach(bills) { bill in
                                        HStack(spacing: 12) {
                                            Image(systemName: bill.type == .income ? "plus.circle" : "minus.circle")
                                                .foregroundColor(.gray)
                                                .font(.title3)
                                            VStack(alignment: .leading, spacing: 2) {
                                                HStack {
                                                    Text(bill.category.rawValue.localized)
                                                        .fontWeight(.semibold)
                                                        .foregroundColor(.primary)
                                                        .lineLimit(1)
                                                        .minimumScaleFactor(0.8)
                                                    if !bill.remark.isEmpty {
                                                        Text(bill.remark)
                                                            .font(.caption)
                                                            .foregroundColor(.secondary)
                                                            .lineLimit(1)
                                                            .minimumScaleFactor(0.8)
                                                    }
                                                }
                                                Text(String(format: "%.2f", bill.amount))
                                                    .font(.body)
                                                    .foregroundColor(.primary)
                                                    .lineLimit(1)
                                                    .minimumScaleFactor(0.8)
                                            }
                                            Spacer()
                                            Text(bill.type.rawValue.localized)
                                                .font(.caption)
                                                .foregroundColor(.secondary)
                                                .lineLimit(1)
                                                .minimumScaleFactor(0.8)
                                        }
                                        .padding(.vertical, 4)
                                        .background(Color.white.opacity(0.001))
                                        .cornerRadius(10)
                                        .onTapGesture {
                                            editBill = bill
                                        }
                                        .transition(.asymmetric(
                                            insertion: .scale.combined(with: .opacity),
                                            removal: .scale.combined(with: .opacity)
                                        ))
                                    }
                                    .onDelete { indexSet in
                                        withAnimation(.easeInOut(duration: 0.3)) {
                                            let realIndex = indexSet.map { bills[$0].id }
                                            self.bills.removeAll { b in realIndex.contains(b.id) }
                                            saveBills()
                                        }
                                    }
                                }
                            }
                        }
                        .listStyle(InsetGroupedListStyle())
                        .animation(.easeInOut(duration: 0.3), value: bills.count)
                    }
                }
                // 悬浮添加按钮（灰色主色）
                Button(action: { 
                    withAnimation(.spring(response: 0.3, dampingFraction: 0.6)) {
                        showAddSheet = true
                    }
                }) {
                    Image(systemName: "plus")
                        .font(.system(size: 28, weight: .bold))
                        .foregroundColor(.white)
                        .padding()
                        .background(
                            Circle().fill(Color.gray)
                        )
                        .shadow(color: Color.gray.opacity(0.2), radius: 8, x: 0, y: 4)
                }
                .padding(.trailing, 28)
                .padding(.bottom, 32)
                .accessibilityLabel("添加账单".localized)
                .scaleEffect(animateAdd ? 1.1 : 1.0)
                .animation(.easeInOut(duration: 0.2), value: animateAdd)
                // 弹窗
                .sheet(isPresented: $showAddSheet) {
                    BillEditView { newBill in
                        withAnimation(.spring(response: 0.5, dampingFraction: 0.7)) {
                            bills.append(newBill)
                            saveBills()
                            animateAdd = true
                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                                animateAdd = false
                            }
                        }
                    }
                }
                .sheet(item: $editBill) { bill in
                    BillEditView(bill: bill) { updatedBill in
                        if let idx = bills.firstIndex(where: { $0.id == updatedBill.id }) {
                            withAnimation(.easeInOut(duration: 0.3)) {
                                bills[idx] = updatedBill
                                saveBills()
                            }
                        }
                    }
                }
            }
            .navigationTitle("账单总览".localized)
        }
        .onAppear {
            self.bills = BillListPage.loadBills()
        }
        .onReceive(NotificationCenter.default.publisher(for: NSNotification.Name("BillsUpdated"))) { _ in
            self.bills = BillListPage.loadBills()
        }
    }
}

struct StatisticsPage: View {
    @EnvironmentObject var languageManager: LanguageManager
    @State private var bills: [Bill] = []
    @State private var selectedTimeRange: TimeRange = .today
    @State private var customStartDate = Date()
    @State private var customEndDate = Date()
    @State private var showDatePicker = false
    
    enum TimeRange: String, CaseIterable {
        case today = "当天"
        case week = "本周"
        case month = "本月"
        case quarter = "本季"
        case year = "本年"
        case custom = "自定义"
        
        var icon: String {
            switch self {
            case .today: return "calendar"
            case .week: return "calendar"
            case .month: return "calendar"
            case .quarter: return "calendar.badge.clock"
            case .year: return "calendar.badge.clock"
            case .custom: return "calendar.badge.plus"
            }
        }
        
        var displayText: String {
            switch self {
            case .today, .week, .month, .quarter, .year:
                return self.rawValue.localized
            case .custom:
                return "自定义".localized
            }
        }
    }
    
    var filteredBills: [Bill] {
        let calendar = Calendar.current
        let now = Date()
        
        switch selectedTimeRange {
        case .today:
            let startOfDay = calendar.startOfDay(for: now)
            let endOfDay = calendar.date(byAdding: .day, value: 1, to: startOfDay) ?? now
            return bills.filter { bill in
                bill.date >= startOfDay && bill.date < endOfDay
            }
        case .week:
            let startOfWeek = calendar.dateInterval(of: .weekOfYear, for: now)?.start ?? now
            return bills.filter { bill in
                bill.date >= startOfWeek && bill.date <= now
            }
        case .month:
            let startOfMonth = calendar.dateInterval(of: .month, for: now)?.start ?? now
            return bills.filter { bill in
                bill.date >= startOfMonth && bill.date <= now
            }
        case .quarter:
            let currentQuarter = (calendar.component(.month, from: now) - 1) / 3
            let startOfQuarter = calendar.date(from: DateComponents(year: calendar.component(.year, from: now), month: currentQuarter * 3 + 1, day: 1)) ?? now
            return bills.filter { bill in
                bill.date >= startOfQuarter && bill.date <= now
            }
        case .year:
            let startOfYear = calendar.dateInterval(of: .year, for: now)?.start ?? now
            return bills.filter { bill in
                bill.date >= startOfYear && bill.date <= now
            }
        case .custom:
            return bills.filter { bill in
                bill.date >= customStartDate && bill.date <= customEndDate
            }
        }
    }
    
    var totalIncome: Double {
        filteredBills.filter { $0.type == .income }.map { $0.amount }.reduce(0, +)
    }
    var totalExpense: Double {
        filteredBills.filter { $0.type == .expense }.map { $0.amount }.reduce(0, +)
    }
    var categorySummary: [(BillCategory, Double)] {
        BillCategory.allCases.map { cat in
            (cat, filteredBills.filter { $0.category == cat }.map { $0.amount }.reduce(0, +))
        }.filter { $0.1 > 0 }
    }
    
    func loadBills() {
        bills = BillListPage.loadBills()
    }
    
    var body: some View {
        NavigationStack {
            ScrollView {
                VStack(spacing: 20) {
                    // 时间筛选器
                    VStack(alignment: .leading, spacing: 8) {
                        Text("时间范围".localized)
                            .font(.headline)
                            .foregroundColor(.primary)
                        
                        ScrollView(.horizontal, showsIndicators: false) {
                            HStack(spacing: 12) {
                                ForEach(TimeRange.allCases, id: \.self) { range in
                                    Button(action: {
                                        selectedTimeRange = range
                                        if range == .custom {
                                            showDatePicker = true
                                        }
                                    }) {
                                        HStack(spacing: 4) {
                                            Image(systemName: range.icon)
                                                .font(.caption)
                                            Text(range.displayText)
                                                .font(.caption)
                                                .fontWeight(.medium)
                                                .lineLimit(1)
                                                .minimumScaleFactor(0.8)
                                        }
                                        .foregroundColor(selectedTimeRange == range ? .white : .primary)
                                        .padding(.horizontal, 8)
                                        .padding(.vertical, 8)
                                        .background(
                                            RoundedRectangle(cornerRadius: 8)
                                                .fill(selectedTimeRange == range ? Color.gray : Color.gray.opacity(0.1))
                                        )
                                    }
                                }
                            }
                            .padding(.horizontal, 4)
                        }
                        
                        // 自定义时间范围显示
                        if selectedTimeRange == .custom {
                            HStack {
                                Text("\(customStartDate, formatter: dateFormatter) - \(customEndDate, formatter: dateFormatter)")
                                    .font(.caption)
                                    .foregroundColor(.secondary)
                                Spacer()
                                Button("修改".localized) {
                                    showDatePicker = true
                                }
                                .font(.caption)
                                .foregroundColor(.gray)
                            }
                            .padding(.top, 4)
                        }
                    }
                    .padding()
                    .frame(maxWidth: .infinity)
                    .background(
                        RoundedRectangle(cornerRadius: 14)
                            .fill(Color(.systemGray6))
                    )
                    .padding(.horizontal)
                    
                    // 收支统计卡片
                    VStack(alignment: .leading, spacing: 8) {
                        Text("收支统计".localized)
                            .font(.headline)
                            .foregroundColor(.primary)
                        
                        HStack {
                            VStack(alignment: .leading) {
                                Text("总收入".localized)
                                    .font(.caption)
                                    .foregroundColor(.secondary)
                                Text("+\(String(format: "%.2f", totalIncome))")
                                    .font(.title2)
                                    .foregroundColor(.primary)
                            }
                            Spacer()
                            VStack(alignment: .leading) {
                                Text("总支出".localized)
                                    .font(.caption)
                                    .foregroundColor(.secondary)
                                Text("-\(String(format: "%.2f", totalExpense))")
                                    .font(.title2)
                                    .foregroundColor(.primary)
                            }
                        }
                    }
                    .padding()
                    .frame(maxWidth: .infinity)
                    .background(
                        RoundedRectangle(cornerRadius: 14)
                            .fill(Color(.systemGray6))
                    )
                    .padding(.horizontal)
                    
                    // 柱状图（灰度渐变）
                    VStack(alignment: .leading, spacing: 8) {
                        Text("分类统计（柱状图）".localized)
                            .font(.headline)
                            .foregroundColor(.primary)
                        if categorySummary.isEmpty {
                            Text("暂无数据".localized)
                                .foregroundColor(.secondary)
                        } else {
                            AnimatedBarChart(data: categorySummary, maxValue: totalIncome + totalExpense)
                        }
                    }
                    .padding()
                    .frame(maxWidth: .infinity)
                    .background(
                        RoundedRectangle(cornerRadius: 14)
                            .fill(Color(.systemGray6))
                    )
                    .padding(.horizontal)
                    
                    // 饼图（灰度分块）
                    VStack(alignment: .leading, spacing: 8) {
                        Text("分类占比（饼图）".localized)
                            .font(.headline)
                            .foregroundColor(.primary)
                        if categorySummary.isEmpty {
                            Text("暂无数据".localized)
                                .foregroundColor(.secondary)
                        } else {
                            PieChartView(data: categorySummary.map { $0.1 }, labels: categorySummary.map { $0.0.rawValue })
                                .frame(height: 180)
                        }
                    }
                    .padding()
                    .frame(maxWidth: .infinity)
                    .background(
                        RoundedRectangle(cornerRadius: 14)
                            .fill(Color(.systemGray6))
                    )
                    .padding(.horizontal)
                }
                .padding(.top)
            }
            .navigationTitle("统计".localized)
            .sheet(isPresented: $showDatePicker) {
                CustomDateRangePicker(
                    startDate: $customStartDate,
                    endDate: $customEndDate
                )
            }
            .onAppear {
                loadBills()
            }
            .onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
                loadBills()
            }
            .onReceive(NotificationCenter.default.publisher(for: NSNotification.Name("BillsUpdated"))) { _ in
                loadBills()
            }
        }
    }
    
    private var dateFormatter: DateFormatter {
        let formatter = DateFormatter()
        formatter.dateFormat = "MM-dd"
        return formatter
    }
}

// 自定义日期范围选择器
struct CustomDateRangePicker: View {
    @EnvironmentObject var languageManager: LanguageManager
    @Environment(\.dismiss) var dismiss
    @Binding var startDate: Date
    @Binding var endDate: Date
    
    var body: some View {
        NavigationView {
            VStack(spacing: 0) {
                // 顶部标题区域
                VStack(spacing: 24) {
                    // 图标 - 稍微小一点，更精致
                    Image(systemName: "calendar.badge.clock")
                        .font(.system(size: 36))
                        .foregroundColor(.gray)
                        .padding(.top, 32)
                    
                    // 标题
                    Text("选择时间范围".localized)
                        .font(.title)
                        .fontWeight(.semibold)
                        .foregroundColor(.primary)
                    
                    // 描述
                    Text("选择要统计的时间区间".localized)
                        .font(.body)
                        .foregroundColor(.secondary)
                        .multilineTextAlignment(.center)
                }
                .padding(.horizontal, 24)
                .padding(.bottom, 40)
                
                // 日期选择器区域
                VStack(spacing: 0) {
                    // 开始日期
                    VStack(alignment: .leading, spacing: 16) {
                        HStack {
                            Image(systemName: "calendar")
                                .foregroundColor(.gray)
                                .font(.title3)
                            Text("开始日期".localized)
                                .font(.headline)
                                .foregroundColor(.primary)
                        }
                        
                        HStack {
                            DatePicker("", selection: $startDate, displayedComponents: .date)
                                .datePickerStyle(CompactDatePickerStyle())
                                .environment(\.locale, Locale(identifier: languageManager.currentLanguage.rawValue))
                                .labelsHidden()
                            
                            Spacer()
                            
                            Image(systemName: "chevron.right")
                                .font(.caption)
                                .foregroundColor(.gray.opacity(0.6))
                        }
                        .padding(.horizontal, 20)
                        .padding(.vertical, 16)
                        .background(
                            RoundedRectangle(cornerRadius: 16)
                                .fill(Color(.systemGray6))
                                .overlay(
                                    RoundedRectangle(cornerRadius: 16)
                                        .stroke(Color.gray.opacity(0.2), lineWidth: 0.5)
                                )
                        )
                    }
                    .padding(.horizontal, 24)
                    .padding(.bottom, 20)
                    
                    // 结束日期
                    VStack(alignment: .leading, spacing: 16) {
                        HStack {
                            Image(systemName: "calendar.badge.plus")
                                .foregroundColor(.gray)
                                .font(.title3)
                            Text("结束日期".localized)
                                .font(.headline)
                                .foregroundColor(.primary)
                        }
                        
                        HStack {
                            DatePicker("", selection: $endDate, displayedComponents: .date)
                                .datePickerStyle(CompactDatePickerStyle())
                                .environment(\.locale, Locale(identifier: languageManager.currentLanguage.rawValue))
                                .labelsHidden()
                            
                            Spacer()
                            
                            Image(systemName: "chevron.right")
                                .font(.caption)
                                .foregroundColor(.gray.opacity(0.6))
                        }
                        .padding(.horizontal, 20)
                        .padding(.vertical, 16)
                        .background(
                            RoundedRectangle(cornerRadius: 16)
                                .fill(Color(.systemGray6))
                                .overlay(
                                    RoundedRectangle(cornerRadius: 16)
                                        .stroke(Color.gray.opacity(0.2), lineWidth: 0.5)
                                )
                        )
                    }
                    .padding(.horizontal, 24)
                }
                
                Spacer()
                
                // 按钮区域
                VStack(spacing: 20) {
                    // 确认按钮 - 更突出的主色调
                    Button(action: { dismiss() }) {
                        HStack(spacing: 10) {
                            Image(systemName: "checkmark")
                                .font(.body)
                                .fontWeight(.semibold)
                            Text("确认选择".localized)
                                .font(.body)
                                .fontWeight(.semibold)
                        }
                        .foregroundColor(.white)
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 18)
                        .background(
                            RoundedRectangle(cornerRadius: 14)
                                .fill(Color.gray.opacity(0.9))
                        )
                        .shadow(color: Color.gray.opacity(0.2), radius: 10, x: 0, y: 5)
                    }
                    
                    // 取消按钮 - 简化为纯文本按钮
                    Button(action: { dismiss() }) {
                        Text("取消".localized)
                            .font(.body)
                            .fontWeight(.medium)
                            .foregroundColor(.gray)
                            .frame(maxWidth: .infinity)
                            .padding(.vertical, 18)
                    }
                }
                .padding(.horizontal, 24)
                .padding(.bottom, 40)
            }
            .navigationTitle("时间范围".localized)
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button(action: { dismiss() }) {
                        Image(systemName: "xmark")
                            .font(.body)
                            .foregroundColor(.gray)
                    }
                }
            }
        }
    }
}

struct SettingsPage: View {
    @EnvironmentObject var themeManager: ThemeManager
    @EnvironmentObject var languageManager: LanguageManager
    @State private var showAlert = false
    @State private var showAbout = false
    @State private var showCustomAlert = false
    @State private var showThemePicker = false
    @State private var showLanguagePicker = false
    @State private var selectedTheme: Theme = .system
    @State private var selectedLanguage: Language = .chinese
    
    enum Theme: String, CaseIterable {
        case light = "light"
        case dark = "dark"
        case system = "system"
        
        var displayName: String {
            switch self {
            case .light: return "浅色".localized
            case .dark: return "深色".localized
            case .system: return "跟随系统".localized
            }
        }
        
        var icon: String {
            switch self {
            case .light: return "sun.max"
            case .dark: return "moon"
            case .system: return "gear"
            }
        }
    }
    
    init() {
        // 从UserDefaults加载主题设置
        if let savedTheme = UserDefaults.standard.string(forKey: "selectedTheme"),
           let theme = Theme(rawValue: savedTheme) {
            _selectedTheme = State(initialValue: theme)
        }
        
        // 从UserDefaults加载语言设置
        if let savedLanguage = UserDefaults.standard.string(forKey: "selectedLanguage"),
           let language = Language(rawValue: savedLanguage) {
            _selectedLanguage = State(initialValue: language)
        }
    }
    
    func saveTheme() {
        UserDefaults.standard.set(selectedTheme.rawValue, forKey: "selectedTheme")
        themeManager.selectedTheme = selectedTheme.rawValue
    }
    
    func saveLanguage() {
        UserDefaults.standard.set(selectedLanguage.rawValue, forKey: "selectedLanguage")
        // 使用语言管理器设置语言
        languageManager.setLanguage(selectedLanguage)
    }
    
    // 移除@AppStorage，统一用UserDefaults
    func loadBills() -> [Bill] {
        if let data = UserDefaults.standard.data(forKey: "bills"),
           let arr = try? JSONDecoder().decode([Bill].self, from: data) {
            return arr
        }
        return []
    }
    
    func clearBills() {
        UserDefaults.standard.set(try! JSONEncoder().encode([Bill]()), forKey: "bills")
        NotificationCenter.default.post(name: NSNotification.Name("BillsUpdated"), object: nil)
    }
    
    var body: some View {
        NavigationStack {
            Form {
                Section(header: Text("外观".localized)) {
                    HStack {
                        Image(systemName: "paintbrush")
                            .foregroundColor(.gray)
                        Text("主题设置".localized)
                            .foregroundColor(.primary)
                        Spacer()
                        Text(selectedTheme.displayName)
                            .foregroundColor(.secondary)
                    }
                    .contentShape(Rectangle())
                    .onTapGesture {
                        showThemePicker = true
                    }
                    
                    HStack {
                        Image(systemName: "globe")
                            .foregroundColor(.gray)
                        Text("语言设置".localized)
                            .foregroundColor(.primary)
                        Spacer()
                        Text(selectedLanguage.displayName)
                            .foregroundColor(.secondary)
                    }
                    .contentShape(Rectangle())
                    .onTapGesture {
                        showLanguagePicker = true
                    }
                }
                
                Section {
                    Button(action: { showCustomAlert = true }) {
                        HStack {
                            Image(systemName: "trash")
                                .foregroundColor(.gray)
                            Text("清空所有账单".localized)
                                .foregroundColor(.red)
                        }
                    }
                }
                
                Section(header: Text("更多".localized)) {
                    Button(action: { showAbout = true }) {
                        HStack {
                            Image(systemName: "info.circle")
                                .foregroundColor(.gray)
                            Text("关于App".localized)
                                .foregroundColor(.primary)
                        }
                    }
                    .sheet(isPresented: $showAbout) {
                        AboutPage()
                    }
                }
            }
            .navigationTitle("设置".localized)
            .sheet(isPresented: $showThemePicker) {
                ThemePickerView(selectedTheme: $selectedTheme, onSave: saveTheme)
            }
            .sheet(isPresented: $showLanguagePicker) {
                LanguagePickerView(selectedLanguage: $selectedLanguage, onSave: saveLanguage)
            }
            .onAppear {
                // 确保selectedTheme与当前主题设置同步
                if let savedTheme = UserDefaults.standard.string(forKey: "selectedTheme"),
                   let theme = Theme(rawValue: savedTheme) {
                    selectedTheme = theme
                }
                
                // 确保selectedLanguage与当前语言设置同步
                if let savedLanguage = UserDefaults.standard.string(forKey: "selectedLanguage"),
                   let language = Language(rawValue: savedLanguage) {
                    selectedLanguage = language
                }
            }
            .overlay(
                // 自定义弹窗
                ZStack {
                    if showCustomAlert {
                        Color.black.opacity(0.4)
                            .ignoresSafeArea()
                            .onTapGesture {
                                showCustomAlert = false
                            }
                        
                        VStack(spacing: 24) {
                            // 警告图标
                            Image(systemName: "exclamationmark.triangle.fill")
                                .font(.system(size: 40))
                                .foregroundColor(.gray)
                                .padding(.top, 20)
                            
                            // 标题
                            Text("确认清空？".localized)
                                .font(.title2)
                                .fontWeight(.semibold)
                                .foregroundColor(.primary)
                            
                            // 描述
                            Text("此操作将删除所有账单数据，且不可恢复。".localized)
                                .font(.body)
                                .foregroundColor(.secondary)
                                .multilineTextAlignment(.center)
                                .padding(.horizontal, 20)
                            
                            // 按钮组
                            HStack(spacing: 16) {
                                // 取消按钮
                                Button(action: {
                                    showCustomAlert = false
                                }) {
                                    Text("取消".localized)
                                        .font(.body)
                                        .fontWeight(.medium)
                                        .foregroundColor(.gray)
                                        .frame(maxWidth: .infinity)
                                        .padding(.vertical, 12)
                                        .background(
                                            RoundedRectangle(cornerRadius: 10)
                                                .fill(Color.gray.opacity(0.1))
                                        )
                                }
                                
                                // 确认按钮
                                Button(action: {
                                    clearBills()
                                    showCustomAlert = false
                                }) {
                                    Text("确认清空".localized)
                                        .font(.body)
                                        .fontWeight(.medium)
                                        .foregroundColor(.white)
                                        .frame(maxWidth: .infinity)
                                        .padding(.vertical, 12)
                                        .background(
                                            RoundedRectangle(cornerRadius: 10)
                                                .fill(Color.gray)
                                        )
                                }
                            }
                            .padding(.horizontal, 20)
                            .padding(.bottom, 20)
                        }
                        .frame(width: 280)
                        .background(
                            RoundedRectangle(cornerRadius: 16)
                                .fill(Color(.systemBackground))
                        )
                        .shadow(color: Color.black.opacity(0.2), radius: 20, x: 0, y: 10)
                        .transition(.scale.combined(with: .opacity))
                    }
                }
                .animation(.easeInOut(duration: 0.3), value: showCustomAlert)
            )
        }
    }
}

// 语言选择器
struct LanguagePickerView: View {
    @Environment(\.dismiss) var dismiss
    @Binding var selectedLanguage: Language
    @EnvironmentObject var languageManager: LanguageManager
    let onSave: () -> Void
    
    var body: some View {
        NavigationStack {
            List {
                ForEach(Language.allCases, id: \.self) { language in
                    HStack {
                        Text(language.flag)
                            .font(.title2)
                            .frame(width: 30)
                        
                        VStack(alignment: .leading, spacing: 2) {
                            Text(language.displayName)
                                .font(.body)
                                .foregroundColor(.primary)
                            
                            Text(language.rawValue)
                                .font(.caption)
                                .foregroundColor(.secondary)
                        }
                        
                        Spacer()
                        
                        if selectedLanguage == language {
                            Image(systemName: "checkmark")
                                .foregroundColor(.gray)
                        }
                    }
                    .contentShape(Rectangle())
                    .onTapGesture {
                        selectedLanguage = language
                        // 立即保存并应用语言
                        languageManager.setLanguage(language)
                        onSave()
                        dismiss()
                    }
                }
            }
            .navigationTitle("语言设置".localized)
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("取消".localized) {
                        dismiss()
                    }
                    .foregroundColor(.gray)
                }
                
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("完成".localized) {
                        onSave()
                        dismiss()
                    }
                    .foregroundColor(.gray)
                }
            }
        }
    }
}



struct ThemePickerView: View {
    @Binding var selectedTheme: SettingsPage.Theme
    let onSave: () -> Void
    @Environment(\.dismiss) var dismiss
    
    var body: some View {
        NavigationView {
            List {
                ForEach(SettingsPage.Theme.allCases, id: \.self) { theme in
                    HStack {
                        Image(systemName: theme.icon)
                            .foregroundColor(.gray)
                            .frame(width: 24)
                        
                        VStack(alignment: .leading, spacing: 2) {
                            Text(theme.displayName)
                                .font(.body)
                                .foregroundColor(.primary)
                            
                            if theme == .system {
                                Text("跟随系统设置".localized)
                                    .font(.caption)
                                    .foregroundColor(.secondary)
                            }
                        }
                        
                        Spacer()
                        
                        if selectedTheme == theme {
                            Image(systemName: "checkmark")
                                .foregroundColor(.gray)
                        }
                    }
                    .contentShape(Rectangle())
                    .onTapGesture {
                        selectedTheme = theme
                        // 立即保存并应用主题
                        DispatchQueue.main.async {
                            onSave()
                        }
                    }
                }
            }
            .navigationTitle("主题设置".localized)
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("取消".localized) {
                        dismiss()
                    }
                    .foregroundColor(.gray)
                }
                
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("完成".localized) {
                        onSave()
                        dismiss()
                    }
                    .foregroundColor(.gray)
                }
            }
        }
    }
}

struct AboutPage: View {
    @EnvironmentObject var languageManager: LanguageManager
    @Environment(\.dismiss) var dismiss
    
    var body: some View {
        NavigationView {
            ScrollView {
                VStack(spacing: 32) {
                    // App图标和名称
                    VStack(spacing: 20) {
                        Image(systemName: "creditcard.fill")
                            .font(.system(size: 50))
                            .foregroundColor(.gray)
                            .frame(width: 90, height: 90)
                            .background(Color.gray.opacity(0.08))
                            .clipShape(Circle())
                            .overlay(
                                Circle()
                                    .stroke(Color.gray.opacity(0.2), lineWidth: 1)
                            )
                        
                        VStack(spacing: 8) {
                            Text("记账助手".localized)
                                .font(.title2)
                                .fontWeight(.semibold)
                                .foregroundColor(.primary)
                            
                            Text("版本 1.0.0".localized)
                                .font(.caption)
                                .foregroundColor(.secondary)
                                .padding(.horizontal, 12)
                                .padding(.vertical, 4)
                                .background(Color.gray.opacity(0.1))
                                .cornerRadius(8)
                        }
                    }
                    .padding(.top, 20)
                    
                    // 功能介绍卡片
                    VStack(alignment: .leading, spacing: 20) {
                        HStack {
                            Image(systemName: "star.fill")
                                .font(.caption)
                                .foregroundColor(.gray)
                            Text("功能介绍".localized)
                                .font(.headline)
                                .foregroundColor(.primary)
                        }
                        
                        VStack(spacing: 16) {
                            FeatureCard(icon: "plus.circle.fill", title: "快速记账".localized, description: "简单易用的账单添加功能".localized, color: .gray)
                            FeatureCard(icon: "chart.bar.fill", title: "数据统计".localized, description: "收支统计和分类分析".localized, color: .gray)
                            FeatureCard(icon: "gear", title: "数据管理".localized, description: "本地存储，数据安全".localized, color: .gray)
                        }
                    }
                    .padding(.horizontal, 20)
                    
                    // 开发者信息卡片
                    VStack(alignment: .leading, spacing: 20) {
                        HStack {
                            Image(systemName: "person.fill")
                                .font(.caption)
                                .foregroundColor(.gray)
                            Text("开发者信息".localized)
                                .font(.headline)
                                .foregroundColor(.primary)
                        }
                        
                        VStack(spacing: 12) {
                            InfoRow(title: "开发者".localized, value: "下坠".localized)
                            InfoRow(title: "开发语言".localized, value: "Swift + SwiftUI".localized)
                            InfoRow(title: "数据存储".localized, value: "本地保存，不联网".localized)
                            InfoRow(title: "设计风格".localized, value: "黑白极简".localized)
                        }
                        .padding(16)
                        .background(Color.gray.opacity(0.05))
                        .cornerRadius(12)
                    }
                    .padding(.horizontal, 20)
                    
                    Spacer(minLength: 40)
                }
            }
            .navigationTitle("关于".localized)
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("关闭".localized) {
                        dismiss()
                    }
                    .foregroundColor(.gray)
                }
            }
        }
    }
}

struct FeatureCard: View {
    let icon: String
    let title: String
    let description: String
    let color: Color
    
    var body: some View {
        HStack(spacing: 16) {
            Image(systemName: icon)
                .font(.title2)
                .foregroundColor(color)
                .frame(width: 32, height: 32)
                .background(color.opacity(0.1))
                .clipShape(Circle())
            
            VStack(alignment: .leading, spacing: 4) {
                Text(title)
                    .font(.subheadline)
                    .fontWeight(.medium)
                    .foregroundColor(.primary)
                
                Text(description)
                    .font(.caption)
                    .foregroundColor(.secondary)
                    .lineLimit(2)
            }
            
            Spacer()
        }
        .padding(16)
        .background(Color.gray.opacity(0.03))
        .cornerRadius(12)
    }
}

struct InfoRow: View {
    let title: String
    let value: String
    
    var body: some View {
        HStack {
            Text(title)
                .font(.caption)
                .foregroundColor(.secondary)
                .frame(width: 80, alignment: .leading)
            
            Text(value)
                .font(.caption)
                .foregroundColor(.primary)
                .fontWeight(.medium)
            
            Spacer()
        }
    }
}

struct BillEditView: View {
    @EnvironmentObject var languageManager: LanguageManager
    @Environment(\.dismiss) var dismiss
    @State private var amount: String
    @State private var type: BillType
    @State private var category: BillCategory
    @State private var remark: String
    @State private var date: Date
    var onSave: (Bill) -> Void
    var bill: Bill?
    @FocusState private var amountFocused: Bool
    @FocusState private var remarkFocused: Bool
    init(bill: Bill? = nil, onSave: @escaping (Bill) -> Void) {
        self.bill = bill
        _amount = State(initialValue: bill != nil ? String(bill!.amount) : "")
        _type = State(initialValue: bill?.type ?? .expense)
        _category = State(initialValue: bill?.category ?? .other)
        _remark = State(initialValue: bill?.remark ?? "")
        _date = State(initialValue: bill?.date ?? Date())
        self.onSave = onSave
    }
    var body: some View {
        ZStack {
            Color(.systemBackground).ignoresSafeArea()
            VStack(spacing: 0) {
                // 顶部关闭按钮（始终可见，避免被键盘遮挡）
                HStack {
                    Spacer()
                    Button(action: { dismiss() }) {
                        Image(systemName: "xmark.circle.fill")
                            .font(.system(size: 28))
                            .foregroundColor(.gray)
                            .padding(8)
                    }
                }
                .padding(.trailing, 8)
                .zIndex(1) // 保证在最上层
                // 输入区卡片
                ScrollView {
                    VStack(spacing: 20) {
                        // 金额输入
                        VStack(alignment: .leading, spacing: 8) {
                            Text("金额".localized)
                                .font(.headline)
                                .foregroundColor(.primary)
                            HStack {
                                Text("¥")
                                    .font(.title)
                                    .foregroundColor(.primary)
                                TextField("0.00", text: $amount)
                                    .font(.system(size: 32, weight: .bold))
                                    .keyboardType(.decimalPad)
                                    .focused($amountFocused)
                                    .onAppear { amountFocused = true }
                            }
                            .padding()
                            .background(
                                RoundedRectangle(cornerRadius: 12)
                                    .stroke(Color.gray.opacity(0.4), lineWidth: 1)
                                    .background(Color(.systemBackground))
                            )
                        }
                        // 类型选择
                        HStack(spacing: 12) {
                            ForEach(BillType.allCases, id: \.self) { t in
                                Button(action: { type = t }) {
                                    Text(t.rawValue.localized)
                                        .font(.title3)
                                        .fontWeight(.semibold)
                                        .foregroundColor(type == t ? .white : .primary)
                                        .frame(maxWidth: .infinity)
                                        .padding(.vertical, 10)
                                        .background(
                                            RoundedRectangle(cornerRadius: 10)
                                                .fill(type == t ? Color.gray : Color.gray.opacity(0.1))
                                        )
                                }
                            }
                        }
                        // 分类选择
                        LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 3), spacing: 12) {
                            ForEach(BillCategory.allCases, id: \.self) { cat in
                                Button(action: { category = cat }) {
                                    VStack(spacing: 4) {
                                        Image(systemName: categoryIcon(for: cat))
                                            .font(.title2)
                                            .foregroundColor(category == cat ? .white : .gray)
                                        Text(cat.rawValue.localized)
                                            .font(.caption)
                                            .foregroundColor(category == cat ? .white : .primary)
                                            .lineLimit(1)
                                            .minimumScaleFactor(0.8)
                                    }
                                    .frame(maxWidth: .infinity)
                                    .padding(.vertical, 10)
                                    .background(
                                        RoundedRectangle(cornerRadius: 10)
                                            .fill(category == cat ? Color.gray : Color.gray.opacity(0.1))
                                    )
                                }
                            }
                        }
                        // 备注输入
                        HStack {
                            TextField("添加备注...".localized, text: $remark, axis: .vertical)
                                .lineLimit(3...6)
                                .focused($remarkFocused)
                            if !remark.isEmpty {
                                Button(action: { remark = "" }) {
                                    Image(systemName: "xmark.circle.fill")
                                        .foregroundColor(.gray)
                                }
                            }
                        }
                        .padding()
                        .background(
                            RoundedRectangle(cornerRadius: 10)
                                .stroke(Color.gray.opacity(0.3), lineWidth: 1)
                                .background(Color(.systemBackground))
                        )
                        // 时间选择
                        DatePicker("", selection: $date, displayedComponents: .date)
                            .datePickerStyle(CompactDatePickerStyle())
                            .environment(\.locale, Locale(identifier: languageManager.currentLanguage.rawValue))
                            .padding(.horizontal)
                    }
                    .padding()
                    .background(
                        RoundedRectangle(cornerRadius: 18)
                            .fill(Color(.systemBackground))
                            .shadow(color: Color.black.opacity(0.08), radius: 16, x: 0, y: 8)
                    )
                    .padding(.horizontal, 16)
                    .padding(.top, 8)
                }
                Spacer()
                // 底部保存按钮
                Button(action: {
                    guard let amt = Double(amount) else { return }
                    let newBill = Bill(id: bill?.id ?? UUID(), amount: amt, type: type, category: category, remark: remark, date: date)
                    onSave(newBill)
                    dismiss()
                }) {
                    Text("保存".localized)
                        .font(.title3)
                        .fontWeight(.bold)
                        .foregroundColor(.white)
                        .frame(maxWidth: .infinity)
        .padding()
                        .background(
                            RoundedRectangle(cornerRadius: 12)
                                .fill(Color.gray)
                        )
                        .shadow(color: Color.gray.opacity(0.2), radius: 8, x: 0, y: 4)
                }
                .padding(.horizontal, 32)
                .padding(.bottom, 24)
            }
        }
    }
    func categoryIcon(for category: BillCategory) -> String {
        switch category {
        case .food: return "fork.knife"
        case .transport: return "car.fill"
        case .shopping: return "bag.fill"
        case .salary: return "dollarsign.circle.fill"
        case .other: return "ellipsis.circle.fill"
        }
    }
}

// 黑白灰极简风格饼图
struct PieChartView: View {
    @EnvironmentObject var languageManager: LanguageManager
    var data: [Double]
    var labels: [String]
    var total: Double { data.reduce(0, +) }
    let grayColors: [Color] = [
        Color.gray.opacity(0.8), Color.gray.opacity(0.6), Color.gray.opacity(0.4), Color.gray.opacity(0.2), Color.gray.opacity(0.1)
    ]
    @State private var animateChart = false
    
    var body: some View {
        GeometryReader { geo in
            ZStack {
                ForEach(0..<data.count, id: \.self) { i in
                    PieSlice(startAngle: angle(at: i), endAngle: angle(at: i+1))
                        .fill(grayColors[i % grayColors.count])
                        .scaleEffect(animateChart ? 1.0 : 0.0)
                        .animation(.easeInOut(duration: 0.8).delay(Double(i) * 0.1), value: animateChart)
                }
                // 中心文字
                VStack {
                    Text("总计".localized)
                        .font(.caption)
                        .foregroundColor(.secondary)
                    Text(String(format: "%.2f", total))
                        .font(.title3)
                        .foregroundColor(.primary)
                }
                .opacity(animateChart ? 1.0 : 0.0)
                .animation(.easeInOut(duration: 0.5).delay(0.5), value: animateChart)
            }
        }
        .onAppear {
            animateChart = true
        }
    }
    func angle(at index: Int) -> Angle {
        let sum = data.prefix(index).reduce(0, +)
        return .degrees(sum / (total == 0 ? 1 : total) * 360 - 90)
    }
}

// 动画柱状图
struct AnimatedBarChart: View {
    let data: [(BillCategory, Double)]
    let maxValue: Double
    @State private var animateBars = false
    
    var body: some View {
        HStack(alignment: .bottom, spacing: 12) {
            ForEach(Array(data.enumerated()), id: \.offset) { item in
                let index = item.offset
                let (cat, sum) = item.element
                VStack {
                    RoundedRectangle(cornerRadius: 4)
                        .fill(LinearGradient(gradient: Gradient(colors: [Color.gray.opacity(0.7), Color.gray.opacity(0.3)]), startPoint: .bottom, endPoint: .top))
                        .frame(width: 24, height: animateBars ? CGFloat(sum / (maxValue + 0.01)) * 120 : 0)
                        .animation(.easeInOut(duration: 0.8).delay(Double(index) * 0.1), value: animateBars)
                    Text(cat.rawValue)
                        .font(.caption2)
                        .foregroundColor(.secondary)
                        .opacity(animateBars ? 1.0 : 0.0)
                        .animation(.easeInOut(duration: 0.3).delay(Double(index) * 0.1 + 0.5), value: animateBars)
                }
            }
        }
        .frame(height: 140)
        .onAppear {
            animateBars = true
        }
    }
}

// 饼图扇形
struct PieSlice: Shape {
    var startAngle: Angle
    var endAngle: Angle
    func path(in rect: CGRect) -> Path {
        var path = Path()
        let center = CGPoint(x: rect.midX, y: rect.midY)
        path.move(to: center)
        path.addArc(center: center, radius: min(rect.width, rect.height)/2, startAngle: startAngle, endAngle: endAngle, clockwise: false)
        path.closeSubpath()
        return path
    }
}

#Preview {
    ContentView()
}
